package com.example.onlineanswer.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;

/**
 * WebSocket专用JWT工具类
 */
@Slf4j
@Component
public class WebSocketJwtUtil {

    private static String secret;
    private static long expiration;

    @Value("${app.jwt.secret-key}")
    public void setSecret(String secretKey) {
        WebSocketJwtUtil.secret = secretKey;
    }

    @Value("${app.jwt.expire-time}")
    public void setExpiration(long expireTime) {
        WebSocketJwtUtil.expiration = expireTime;
    }

    /**
     * 从token中获取用户ID
     */
    public static Long getUserId(String token) {
        try {
            return Long.parseLong(getClaimFromToken(token, Claims::getSubject));
        } catch (Exception e) {
            log.error("从token中获取用户ID失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 从token中获取失效时间
     */
    public static Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从token中获取指定的声明信息
     */
    public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 解析token获取所有声明信息
     */
    private static Claims getAllClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    /**
     * 检查token是否过期
     */
    private static Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 生成token
     */
    public static String generateToken(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userId.toString());
    }

    /**
     * 生成token的具体实现
     */
    private static String doGenerateToken(Map<String, Object> claims, String subject) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 验证token
     */
    public static Boolean validateToken(String token) {
        try {
            return !isTokenExpired(token);
        } catch (Exception e) {
            log.error("验证token失败: {}", e.getMessage());
            return false;
        }
    }
} 